<template>
  <main-layout>
    <div class="cart-page">
      <div class="container">
        <h1>购物车</h1>

        <div v-if="$store.state.cart.length > 0" class="cart-content">
          <div class="cart-items">
            <div class="cart-header">
              <label class="select-all">
                <input type="checkbox" :checked="selectAll" @change="handleSelectAllChange">
                <span>全选</span>
              </label>
              <span class="header-item">商品信息</span>
              <span class="header-item">单价</span>
              <span class="header-item">数量</span>
              <span class="header-item">小计</span>
              <span class="header-item">操作</span>
            </div>

            <transition-group name="cart-item" tag="div" class="cart-items-list">
              <div
                v-for="item in $store.state.cart"
                :key="item.id"
                class="cart-item"
              >
                <div class="item-select">
                  <input type="checkbox" :checked="item.selected" @change="handleItemSelectChange(item)">
                </div>
                <div class="item-image">
                  <img :src="item.image" :alt="item.name" />
                </div>
                <div class="item-info">
                  <h3>{{ item.name }}</h3>
                  <p class="item-desc">{{ item.description }}</p>
                  <div class="item-tags">
                    <span v-for="tag in item.tags" :key="tag" class="tag">
                      {{ tag }}
                    </span>
                  </div>
                </div>
                <div class="item-price">¥{{ item.price }}</div>
                <div class="item-quantity">
                  <div class="quantity-control">
                    <button
                      @click="decreaseQuantity(item)"
                      :disabled="item.quantity <= 1"
                      class="quantity-btn"
                    >
                      <i class="fas fa-minus"></i>
                    </button>
                    <input
                      type="number"
                      v-model.number="item.quantity"
                      min="1"
                      :max="item.stock"
                      @change="validateQuantity(item)"
                    />
                    <button
                      @click="increaseQuantity(item)"
                      :disabled="item.quantity >= item.stock"
                      class="quantity-btn"
                    >
                      <i class="fas fa-plus"></i>
                    </button>
                  </div>
                  <div class="stock-info" :class="{ 'low-stock': item.stock < 10 }">
                    库存: {{ item.stock }}
                  </div>
                </div>
                <div class="item-total">¥{{ item.price * item.quantity }}</div>
                <div class="item-actions">
                  <button class="save-later" @click="saveForLater(item)">
                    <i class="far fa-bookmark"></i>
                  </button>
                  <button class="remove-btn" @click="removeItem(item)">
                    <i class="fas fa-trash"></i>
                  </button>
                </div>
              </div>
            </transition-group>

            <div class="saved-items" v-if="savedItems.length">
              <h3>稍后购买</h3>
              <div class="saved-items-list">
                <div v-for="item in savedItems" :key="item.id" class="saved-item">
                  <img :src="item.image" :alt="item.name" />
                  <div class="saved-item-info">
                    <h4>{{ item.name }}</h4>
                    <p class="price">¥{{ item.price }}</p>
                  </div>
                  <button class="move-to-cart" @click="moveToCart(item)">
                    移入购物车
                  </button>
                  <button class="remove-saved" @click="removeSavedItem(item)">
                    <i class="fas fa-times"></i>
                  </button>
                </div>
              </div>
            </div>
          </div>

          <div class="cart-summary" :class="{ 'sticky': isMobile }">
            <div class="summary-item">
              <span>已选商品</span>
              <span>{{ selectedCount }}件</span>
            </div>
            <div class="summary-item">
              <span>商品总价</span>
              <span>¥{{ selectedTotal }}</span>
            </div>
            <div class="summary-item">
              <span>运费</span>
              <span>免运费</span>
            </div>
            <div class="summary-item discount" v-if="discount > 0">
              <span>优惠</span>
              <span>-¥{{ discount }}</span>
            </div>
            <div class="summary-total">
              <span>应付总额</span>
              <span>¥{{ selectedTotal - discount }}</span>
            </div>
            <button 
              class="checkout-btn" 
              @click="checkout"
              :disabled="selectedCount === 0"
            >
              立即结算 ({{ selectedCount }}件)
            </button>
          </div>
        </div>

        <div v-else class="empty-cart">
          <div class="empty-cart-content">
            <img
              src="https://gw.alicdn.com/tfs/TB1P3WnQpzqK1RjSZFCXXbbxVXa-520-280.png"
              alt="空购物车"
              class="empty-cart-image"
            />
            <h2>购物车还是空的</h2>
            <p>快去挑选心仪的商品吧~</p>
            <router-link to="/products" class="continue-shopping">
              继续购物
            </router-link>
          </div>
        </div>
      </div>
    </div>
  </main-layout>
</template>

<script>
import MainLayout from "@/components/layouts/MainLayout.vue";
import Vue from 'vue'; // Import Vue for Vue.set

export default {
  name: "CartView",
  components: {
    MainLayout,
  },
  data() {
    return {
      discount: 0,
      savedItems: [],
      isMobile: false,
    };
  },
  computed: {
    selectAll() {
      return this.$store.state.cart.length > 0 && 
             this.$store.state.cart.every(item => item.selected);
    },
    selectedCount() {
      return this.$store.state.cart
        .filter(item => item.selected)
        .reduce((count, item) => count + item.quantity, 0);
    },
    selectedTotal() {
      return this.$store.state.cart
        .filter(item => item.selected)
        .reduce((total, item) => total + item.price * item.quantity, 0);
    }
  },
  methods: {
    handleSelectAllChange(event) {
      const selected = event.target.checked;
      this.$store.commit('setAllCartItemsSelected', selected);
    },
    handleItemSelectChange(item) {
      const selected = !item.selected;
      this.$store.commit('setCartItemSelected', { itemId: item.id, selected });
    },
    validateQuantity(item) {
      let newQuantity = item.quantity;
      if (newQuantity < 1) {
        newQuantity = 1;
      } else if (newQuantity > item.stock) {
        newQuantity = item.stock;
      }
      if (newQuantity !== item.quantity) {
        this.$store.commit('setCartItemQuantity', { itemId: item.id, quantity: newQuantity });
      }
    },
    decreaseQuantity(item) {
      if (item.quantity > 1) {
        this.$store.commit('setCartItemQuantity', { itemId: item.id, quantity: item.quantity - 1 });
      }
    },
    increaseQuantity(item) {
      if (item.quantity < item.stock) {
        this.$store.commit('setCartItemQuantity', { itemId: item.id, quantity: item.quantity + 1 });
      }
    },
    removeItem(item) {
      if (confirm("确定要删除这个商品吗？")) {
        this.$store.commit("removeFromCart", item);
      }
    },
    saveForLater(item) {
      this.savedItems.push({...item});
      this.$store.commit("removeFromCart", item);
    },
    moveToCart(item) {
      this.$store.commit("addToCart", item);
      this.removeSavedItem(item);
    },
    removeSavedItem(item) {
      const index = this.savedItems.findIndex(i => i.id === item.id);
      if (index > -1) {
        this.savedItems.splice(index, 1);
      }
    },
    async checkout() {
      if (this.selectedCount === 0) {
        alert('请选择要结算的商品！');
        return;
      }

      const selectedItems = this.$store.state.cart.filter(item => item.selected);

      if (selectedItems.length === 0) {
        alert('请选择要结算的商品！');
        return;
      }

      // 生成订单对象
      const newOrder = {
        id: 'DD' + Date.now(), // 简单的订单ID生成
        number: 'DD' + Date.now(),
        status: 'completed', // 初始状态直接设置为已完成
        statusText: '已完成',
        products: selectedItems.map(item => ({
          id: item.id,
          name: item.name,
          price: item.price,
          quantity: item.quantity,
          image: item.image,
        })),
        totalQuantity: this.selectedCount,
        totalAmount: this.selectedTotal,
        orderDate: new Date().toISOString(),
      };

      // 模拟结算过程
      alert('结算成功！');

      // 将订单添加到用户订单历史
      await this.$store.dispatch('addOrder', newOrder);

      // 清空购物车中已选中的商品
      this.$store.commit('setCart', this.$store.state.cart.filter(item => !item.selected));

      // 跳转到个人中心的订单页面
      this.$router.push({ path: '/user', query: { menu: 'orders' } });
    },
    checkMobile() {
      this.isMobile = window.innerWidth <= 768;
    }
  },
  mounted() {
    this.checkMobile();
    window.addEventListener('resize', this.checkMobile);
    if (this.$store.state.cart && this.$store.state.cart.length > 0) {
      this.$store.state.cart.forEach(item => {
        if (item.selected === undefined) {
          Vue.set(item, 'selected', true);
        }
      });
    }
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.checkMobile);
  }
};
</script>

<style scoped>
.cart-page {
  padding: 40px 0;
  background: #f8f9fa;
  min-height: calc(100vh - 200px);
}

.cart-page h1 {
  margin-bottom: 30px;
  color: #333;
}

.cart-content {
  display: grid;
  grid-template-columns: 1fr 300px;
  gap: 30px;
}

.cart-header {
  display: grid;
  grid-template-columns: 60px 120px 2fr 1fr 1fr 1fr auto;
  align-items: center;
  padding: 15px 20px;
  background: #f8f9fa;
  border-radius: 8px 8px 0 0;
  font-weight: 500;
  color: #666;
}

.header-item {
  text-align: center;
}

.cart-items {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.cart-items-list {
  position: relative;
}

.cart-item {
  display: grid;
  grid-template-columns: 60px 120px 2fr 1fr 1fr 1fr auto;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #eee;
  gap: 20px;
}

.select-all {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
}

.item-select {
  display: flex;
  justify-content: center;
}

.item-image {
  width: 100px;
  height: 100px;
  overflow: hidden;
  border-radius: 4px;
}

.item-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.item-info h3 {
  font-size: 16px;
  color: #333;
  margin-bottom: 8px;
}

.item-desc {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.item-tags {
  display: flex;
  gap: 8px;
}

.tag {
  padding: 2px 8px;
  background: #ff6b6b;
  color: white;
  border-radius: 4px;
  font-size: 12px;
}

.item-price,
.item-total {
  font-size: 18px;
  color: #ff6b6b;
  font-weight: bold;
  text-align: center;
}

.quantity-control {
  display: flex;
  align-items: center;
  border: 1px solid #ddd;
  border-radius: 4px;
  overflow: hidden;
}

.quantity-btn {
  width: 32px;
  height: 32px;
  border: none;
  background: #f8f9fa;
  color: #666;
  cursor: pointer;
  transition: all 0.3s;
}

.quantity-btn:hover:not(:disabled) {
  background: #ff6b6b;
  color: white;
}

.quantity-btn:disabled {
  color: #ccc;
  cursor: not-allowed;
}

.quantity-control input {
  width: 50px;
  height: 32px;
  border: none;
  border-left: 1px solid #ddd;
  border-right: 1px solid #ddd;
  text-align: center;
  font-size: 14px;
}

.stock-info {
  font-size: 12px;
  color: #666;
  margin-top: 4px;
  text-align: center;
}

.low-stock {
  color: #ff6b6b;
}

.item-actions {
  display: flex;
  gap: 10px;
  justify-content: center;
}

.save-later,
.remove-btn {
  width: 36px;
  height: 36px;
  border: none;
  background: none;
  color: #999;
  transition: all 0.3s;
  cursor: pointer;
}

.save-later:hover,
.remove-btn:hover {
  color: #ff6b6b;
  transform: scale(1.1);
}

.saved-items {
  padding: 20px;
  border-top: 1px solid #eee;
}

.saved-items h3 {
  font-size: 16px;
  color: #333;
  margin-bottom: 15px;
}

.saved-items-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 15px;
}

.saved-item {
  background: #f8f9fa;
  border-radius: 4px;
  padding: 10px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.saved-item img {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border-radius: 4px;
}

.saved-item-info {
  text-align: center;
}

.saved-item-info h4 {
  font-size: 14px;
  color: #333;
  margin-bottom: 5px;
}

.saved-item-info .price {
  color: #ff6b6b;
  font-weight: bold;
}

.move-to-cart {
  width: 100%;
  padding: 8px;
  background: #ff6b6b;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background 0.3s;
}

.move-to-cart:hover {
  background: #ff5252;
}

.remove-saved {
  position: absolute;
  top: 5px;
  right: 5px;
  width: 24px;
  height: 24px;
  border: none;
  background: none;
  color: #999;
  cursor: pointer;
  transition: color 0.3s;
}

.remove-saved:hover {
  color: #ff6b6b;
}

.cart-summary {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  height: fit-content;
}

.cart-summary.sticky {
  position: sticky;
  top: 20px;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
  color: #666;
}

.summary-total {
  display: flex;
  justify-content: space-between;
  margin: 20px 0;
  padding-top: 20px;
  border-top: 1px solid #eee;
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.checkout-btn {
  width: 100%;
  padding: 15px;
  background: #ff6b6b;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  transition: all 0.3s;
  cursor: pointer;
}

.checkout-btn:hover:not(:disabled) {
  background: #ff5252;
  transform: translateY(-2px);
}

.checkout-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.empty-cart {
  text-align: center;
  padding: 60px 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.empty-cart-content {
  max-width: 400px;
  margin: 0 auto;
}

.empty-cart-image {
  width: 200px;
  margin-bottom: 30px;
  animation: float 3s ease-in-out infinite;
}

.empty-cart h2 {
  font-size: 24px;
  color: #333;
  margin-bottom: 10px;
}

.empty-cart p {
  color: #666;
  margin-bottom: 30px;
}

.continue-shopping {
  display: inline-block;
  padding: 12px 30px;
  background: #ff6b6b;
  color: white;
  border-radius: 4px;
  transition: all 0.3s;
}

.continue-shopping:hover {
  background: #ff5252;
  transform: translateY(-2px);
}

.discount {
  color: #ff6b6b;
}

/* Animations */
.cart-item-enter-active,
.cart-item-leave-active {
  transition: all 0.3s ease;
}

.cart-item-enter,
.cart-item-leave-to {
  opacity: 0;
  transform: translateX(30px);
}

@keyframes float {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-10px);
  }
}

@media (max-width: 992px) {
  .cart-content {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .cart-header {
    display: none;
  }

  .cart-item {
    grid-template-columns: 1fr;
    grid-template-areas:
      "select image info"
      "select image price"
      "quantity quantity quantity"
      "total total total"
      "actions actions actions";
    gap: 10px;
    padding: 15px;
  }

  .item-select {
    grid-area: select;
  }

  .item-image {
    grid-area: image;
    width: 80px;
    height: 80px;
  }

  .item-info {
    grid-area: info;
  }

  .item-price {
    grid-area: price;
    text-align: left;
  }

  .item-quantity {
    grid-area: quantity;
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  .item-total {
    grid-area: total;
    text-align: right;
  }

  .item-actions {
    grid-area: actions;
  }

  .cart-summary.sticky {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    top: auto;
    border-radius: 0;
    z-index: 100;
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  }

  .cart-summary.sticky::before {
    content: '';
    position: absolute;
    top: -20px;
    left: 0;
    right: 0;
    height: 20px;
    background: linear-gradient(transparent, rgba(0, 0, 0, 0.1));
  }
}
</style> 